#include "library.h"

Library::Library(int capacity) :
    QObject(0), m_capacity(capacity)
{
}

int Library::size()
{
    return mutexes.size();
}

bool Library::takeBookForReading(book_id_t id)
{
//    QMutexLocker lock(&booksMutex);
    if (id < 0 || id >= mutexes.size())
    {
        return false;
    }
    return mutexes.at(id)->tryLock();
}

void Library::returnReadBook(book_id_t id)
{
    mutexes.at(id)->unlock();
}

book_id_t Library::reserveBookToWrite()
{
    QMutexLocker lock(&booksMutex);
    mutexes.append(new QMutex());
    mutexes.at(mutexes.size()-1)->lock();

    return mutexes.size()-1;
}

void Library::publishWrittenBook(book_id_t id)
{
    mutexes.at(id)->unlock();
    emit finishedWritingBook();
}

void Library::takeBookForEditing(book_id_t id)
{
    emit waitingForBook();
    mutexes.at(id)->lock();
}

void Library::returnEditedBook(book_id_t id)
{
    mutexes.at(id)->unlock();
    emit finishedEditingBook();
}
